package com.itheima.controller;

import com.itheima.common.entity.Result;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class FileUploadController {

    @Value("${health.alioss.endpoint}")
    private String endpoint;
    @Value("${health.alioss.access-key-id}")
    private String accessKeyId;
    @Value("${health.alioss.access-key-secret}")
    private String accessKeySecret;
    @Value("${health.alioss.bucket-name}")
    private String bucketName;

    @Autowired
    private ImageService imageService;


    @PostMapping("/upload")
    public Result upload(MultipartFile imgFile){
        AliOssUtil aliOssUtil = new AliOssUtil(endpoint,accessKeyId,accessKeySecret,bucketName);
        //原始文件名
        String originalFilename = imgFile.getOriginalFilename();
        //截取原始扩展名的后缀  .png
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //构造新文件名称
        String objectName = UUID.randomUUID().toString() + extension;
        String url = "";

        try {
            url = aliOssUtil.upload(imgFile.getBytes(),objectName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 上传成功的图片地址保存到redis缓存中
        imageService.saveUploadedImage(url);

        return new Result(true,"图片上传成功",url);
    }

}
